package com.wocai.jrt.orgadmin.product.action;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.inject.Inject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.vteba.utils.id.ObjectId;
import com.vteba.web.action.GenericAction;
import com.vteba.web.action.JsonBean;
import com.vteba.web.editer.DoubleEditor;
import com.vteba.web.editer.IntEditor;
import com.vteba.web.editer.LongEditor;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.orgadmin.product.model.ProductAttachment;
import com.wocai.jrt.orgadmin.product.service.spi.ProductAttachmentService;
import com.wocai.jrt.orgadmin.product.service.spi.ProductService;
import com.wocai.jrt.orgadmin.utils.MyFileUtils;

/**
 * 产品附件控制器
 * 
 * @author yinlei
 * @date 2015-8-13 16:43:27
 */
@Controller
@RequestMapping("/productAttachment")
public class ProductAttachmentAction extends GenericAction<ProductAttachment> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ProductAttachmentAction.class);
	private static final Pattern FILE = Pattern.compile("^(.*)+.(doc|pdf|txt|docx|xlsx|xls)$");

	@Inject
	private ProductAttachmentService productAttachmentServiceImpl;

	@Inject
	private ProductService productServiceImpl;

	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		// 空字符串转换为null
		binder.registerCustomEditor(int.class, new IntEditor());
		binder.registerCustomEditor(long.class, new LongEditor());
		binder.registerCustomEditor(double.class, new DoubleEditor());
		binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat(
				"yyyy-MM-dd"), true));
	}

	/***
	 * relatedFile相当于list，它只是返回一个页面而已
	 * 
	 * @param productId
	 * @param maps
	 * @return
	 */
	@RequestMapping("/relatedFile/{productId}")
	public String relatedFile(@PathVariable("productId") String productId, Map<String, Object> maps) {
		putRelatedFile(productId, maps);
		return "product/relatedFile";
	}

	/****
	 * query是根据产品id获取它的相关附件列表
	 * 
	 * @param productId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/query/{productId}")
	public JsonBean query(@PathVariable("productId") String productId) {
		JsonBean jsonBean = new JsonBean();
		try {
			LOGGER.info("request relatedFile list, productId=[{}]", productId);

			Map<String, Object> maps = new HashMap<String, Object>();
			putRelatedFile(productId, maps);
			jsonBean.setCode(1);
			jsonBean.setData(maps);
			jsonBean.setMessage(SUCCESS);
			return jsonBean;
		} catch (Exception e) {
			LOGGER.error("request relatedFile list error, msg=[{}]", e.getMessage());
			jsonBean.setCode(0);
			jsonBean.setMessage("request relatedFile list error");
			return jsonBean;
		}
	}

	private void putRelatedFile(String productId, Map<String, Object> maps) {
		List<ProductAttachment> list = new ArrayList<ProductAttachment>();
		if (!StringUtils.isBlank(productId)) {
			ProductAttachment paParam = new ProductAttachment();
			paParam.setProductId(productId);
			list = productAttachmentServiceImpl.pagedList(paParam);
			maps.put("product", productServiceImpl.get(productId));
		}
		maps.put("relatedFile", list);// 将model放入视图中，供页面视图使用
	}

	/**
	 * 更新产品附件信息
	 * 
	 * @param model
	 *            要更新的产品附件信息，含有ID
	 * @return 操作结果信息
	 */
	@ResponseBody
	@RequestMapping("/rename")
	public JsonBean rename(ProductAttachment model) {
		JsonBean jsonBean = new JsonBean();
		try {
			String id = model.getId();
			String filename = model.getFileName();// 前端传过来是没有带后缀
			LOGGER.info("request update file name, id=[{}],filename=[{}]", id, filename);

			if (!StringUtils.isBlank(id) && !StringUtils.isBlank(filename)) {
				ProductAttachment productAttachment = productAttachmentServiceImpl.get(id);
				String oldFilename = productAttachment.getFileName();
				LOGGER.info("query productAttachment by id, id=[{}],filename=[{}]", id, oldFilename);

				filename = filename + productAttachment.getFileType();// 补上后缀
				if (!filename.equalsIgnoreCase(oldFilename)) {// 文件如果不存在则先通过页面删除
					String filepath = productAttachment.getFilePath();
					File file = new File(filepath);
					if (file.exists()) {
						String newFilepath = filepath.replace(oldFilename, filename);
						File newFile = new File(newFilepath);
						boolean flag = file.renameTo(newFile);
						if (flag) {
							model.setFileName(filename);
							model.setFilePath(newFilepath);
							int result = productAttachmentServiceImpl.updateById(model);
							if (result == 1) {
								jsonBean.setMessage(SUCCESS);
								jsonBean.setCode(1);
								LOGGER.info("update record success.");
							} else {
								jsonBean.setMessage(ERROR);
								LOGGER.error("update record error.");
							}
						}
					}
				}
			}

		} catch (Exception e) {
			LOGGER.error("update record error, errorMsg=[{}].", e.getMessage());
			jsonBean.setMessage(ERROR);
		}
		return jsonBean;
	}

	/**
	 * 删除产品附件信息
	 * 
	 * @param id
	 *            要删除的产品附件ID
	 */
	@ResponseBody
	@RequestMapping("/delete")
	public JsonBean delete(String id) {
		JsonBean bean = new JsonBean();
		try {
			File file = new File(productAttachmentServiceImpl.get(id).getFilePath());

			if (file.exists()) {
				File parent = file.getParentFile();
				if (file.delete()) {
					parent.delete();
				}
			}

			int result = productAttachmentServiceImpl.deleteById(id);

			if (result == 1) {
				bean.setMessage(SUCCESS);
				bean.setCode(1);
				LOGGER.info("delete record success, id=[{}].", id);
			} else {
				bean.setMessage(ERROR);
				LOGGER.error("delete record error.");
			}
		} catch (Exception e) {
			LOGGER.error("delete record error, id=[{}], errorMsg=[{}].", id, e.getMessage());
			bean.setMessage(ERROR);
		}
		return bean;
	}

	/***
	 * 上传文件 用@RequestParam注解来指定表单上的file为MultipartFile
	 * 
	 * @param file
	 * @param flag
	 *            1 - 正面，0 - 反面
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/uploadRelatedFile")
	public JsonBean uploadRelatedFile(@RequestParam("relatedFile") MultipartFile file, String productId) {
		JsonBean jsonBean = new JsonBean();

		try {
			if (StringUtils.isBlank(productId)) {
				LOGGER.info("productId is not allowed null");
				jsonBean.setCode(0);
				jsonBean.setMessage("产品id不能为空！");
				getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
				return jsonBean;
			}

			String fileName = file.getOriginalFilename();
			if (!FILE.matcher(fileName).matches()) {
				LOGGER.info("request file type not mach the required");
				jsonBean.setCode(0);
				jsonBean.setMessage("不能上传非法格式文件！");
				getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
				return jsonBean;
			}

			ProductAttachment paParam = new ProductAttachment();
			paParam.setProductId(productId);
			paParam.setFileName(fileName);
			List<ProductAttachment> result = productAttachmentServiceImpl.pagedList(paParam);
			if (null != result && result.size() > 0) {
				LOGGER.info("request file have existed");
				jsonBean.setCode(0);
				jsonBean.setMessage("不能重复上传相同文件！");
				getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
				return jsonBean;
			}

			// 发起请求的参数
			LOGGER.info("request file upload, filename=[{}]", fileName);

			// 上传身份证
			String filePath = MyFileUtils.uploadFile(file, MyFileUtils.FILE_TYPE);
			LOGGER.info("upload file success, filePath=[{}]", filePath);

			ProductAttachment productAttachment = new ProductAttachment();
			productAttachment.setId(ObjectId.get().toString());
			productAttachment.setProductId(productId);
			productAttachment.setFilePath(filePath);

			productAttachment.setFileName(fileName);
			productAttachment.setFileType("." + fileName.split("\\.")[1]);
			String orgId = productServiceImpl.get(productId).getOrgId();
			productAttachment.setOrgId(orgId);
			productAttachment.setCreateTime(new Date());
			productAttachmentServiceImpl.save(productAttachment);

			jsonBean.setCode(1);
			jsonBean.setMessage(SUCCESS);

			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		} catch (Exception e) {
			LOGGER.error("upload file error, error=[{}]", e.getMessage());
			jsonBean.setCode(0);
			jsonBean.setMessage("上传失败！");
			getHttpServletResponse().setHeader("X-Frame-Options", "SAMEORIGIN");
		}

		return jsonBean;

	}
}
